"""
景点管理后台
"""
from django.contrib import admin
from .models import Attraction, AttractionImage, AttractionReview, AttractionFavorite


@admin.register(Attraction)
class AttractionAdmin(admin.ModelAdmin):
    list_display = ('name', 'category', 'address', 'ticket_price', 'popularity', 'rating', 'images_count', 'amap_images_count', 'created_at')
    list_filter = ('category', 'popularity', 'rating', 'created_at')
    search_fields = ('name', 'address', 'description', 'amap_poi_id')
    ordering = ('-popularity', 'name')
    readonly_fields = ('amap_poi_id', 'amap_image_urls', 'images_count', 'amap_images_count', 'created_at', 'updated_at')
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'description', 'category', 'address')
        }),
        ('位置信息', {
            'fields': ('latitude', 'longitude', 'amap_poi_id')
        }),
        ('价格和时间', {
            'fields': ('ticket_price', 'open_time', 'close_time', 'visit_time')
        }),
        ('统计信息', {
            'fields': ('popularity', 'rating', 'images_count', 'amap_images_count')
        }),
        ('高德地图数据', {
            'fields': ('amap_image_urls',),
            'classes': ('collapse',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at')
        }),
    )
    
    def images_count(self, obj):
        """本地图片数量"""
        return obj.images.count()
    images_count.short_description = '本地图片'
    
    def amap_images_count(self, obj):
        """高德地图图片数量"""
        if obj.amap_image_urls:
            return len(obj.amap_image_urls)
        return 0
    amap_images_count.short_description = '高德图片'
    
    actions = ['sync_from_amap', 'clear_cache']
    
    def sync_from_amap(self, request, queryset):
        """从高德地图同步选中景点的详细信息"""
        from utils.amap_client import AMapClient
        from django.conf import settings
        
        api_key = settings.AMAP_CONFIG.get('API_KEY')
        if not api_key:
            self.message_user(request, '高德地图API Key未配置', level='error')
            return
        
        amap_client = AMapClient(api_key)
        updated = 0
        
        for attraction in queryset:
            if not attraction.amap_poi_id:
                continue
            
            try:
                poi_detail = amap_client.get_poi_detail(attraction.amap_poi_id)
                if poi_detail.get('status') == '1' and poi_detail.get('pois'):
                    poi_data = poi_detail['pois'][0]
                    
                    # 更新图片
                    photos = poi_data.get('photos', [])
                    if photos:
                        image_urls = []
                        for photo in photos[:10]:
                            if isinstance(photo, dict) and photo.get('url'):
                                url = photo['url']
                                if not url.startswith('http'):
                                    url = 'https://restapi.amap.com' + url
                                image_urls.append(url)
                        
                        if image_urls:
                            attraction.amap_image_urls = image_urls
                            attraction.save(update_fields=['amap_image_urls'])
                            updated += 1
            except Exception as e:
                self.message_user(request, f'同步 {attraction.name} 失败: {str(e)}', level='warning')
        
        self.message_user(request, f'成功更新 {updated} 个景点的图片信息')
    sync_from_amap.short_description = '从高德地图同步图片信息'
    
    def clear_cache(self, request, queryset):
        """清除选中景点的缓存"""
        from django.core.cache import cache
        
        cleared = 0
        for attraction in queryset:
            cache_key = f'attraction_detail_{attraction.id}'
            cache.delete(cache_key)
            cleared += 1
        
        # 清除列表缓存
        if hasattr(cache, 'delete_pattern'):
            cache.delete_pattern('attractions_list_*')
        else:
            cache.clear()
        
        self.message_user(request, f'已清除 {cleared} 个景点的缓存')
    clear_cache.short_description = '清除缓存'


@admin.register(AttractionImage)
class AttractionImageAdmin(admin.ModelAdmin):
    list_display = ('attraction', 'is_primary', 'created_at')
    list_filter = ('is_primary', 'created_at')
    search_fields = ('attraction__name',)
    ordering = ('-is_primary', '-created_at')


@admin.register(AttractionReview)
class AttractionReviewAdmin(admin.ModelAdmin):
    list_display = ('user', 'attraction', 'rating', 'created_at')
    list_filter = ('rating', 'created_at')
    search_fields = ('user__username', 'attraction__name', 'content')
    ordering = ('-created_at',)


@admin.register(AttractionFavorite)
class AttractionFavoriteAdmin(admin.ModelAdmin):
    list_display = ('user', 'attraction', 'created_at')
    list_filter = ('created_at',)
    search_fields = ('user__username', 'attraction__name')
    ordering = ('-created_at',)

